package com.example.fashion.android.globar;

import java.util.Stack;


import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class AppManager {
    // 用一个栈结构来保存窗体，能够依次退出
    public Stack<Activity> activities;
    private static AppManager instance;

    private AppManager() {
        activities = new Stack<Activity>();
    }

    public static AppManager getInstance() {
        if (instance == null) {
            instance = new AppManager();
        }
        return instance;
    }

    /**
     * 定义一个方法用于当每次打开新窗体时压入栈中保存
     * @param activity
     */
    public void addActivity(Activity activity) {
        activities.push(activity);
    }

    /**
     * 只要窗体栈中的窗体没有弹出干净，就按先进后出的顺序弹栈
     */
    public void exit() {
        while (!activities.isEmpty()) {
            Activity activity = activities.pop();
            if (activity.isFinishing()) {

            } else {
                activity.finish();
            }
        }
        // 窗体栈清空后结束应用进程
        System.exit(0);
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activities.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activities.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 获得当前版本名
     *
     * @param context
     * @return
     */
    public static String getCurrentVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获得包信息
     * @param context
     * @return
     */
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;

        try {
            String e = context.getPackageName();
            info = context.getPackageManager().getPackageInfo(e, 0);
        } catch (Exception var3) {
            var3.printStackTrace();
        }
        return info;
    }

}
